import { HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { SelectList } from 'src/Model/SelectList';
import { TaskItems } from 'src/Model/TaskItems';
import { AjaxServiceService } from 'src/services/AjaxService.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(private ajax: AjaxServiceService, private message: NzMessageService, private router: Router) { }

  ngOnInit() {
    this.searchData();
  }
  checked = false;
  indeterminate = false;
  setOfCheckedId = new Set<number>();
  visible = false;
  loading = false;
  urlmehtod = true;
  lucy: string = "";
  item = new TaskItems();
  //model 相关
  isModelVisible = false;
  //表格相关
  total = 0;
  pageindex = 1;
  pagesize = 10;
  tableloading = false;
  listOfCurrentPageData: TaskItems[] = [];

   //任务日志表格
   logtotal = 0;
   logpageindex = 1;
   logpagesize = 10;
   logtableloading = false;
   logcurrentdata :any[]= [];

   //下拉框
  sshoptionlist:SelectList[] | undefined;

  searchData(reset: boolean = false) {
    if (reset) {
      this.pageindex = 1;
    }
    this.tableloading = true;
    let params = new HttpParams();
    params = params.append("PageIndex", this.pageindex.toString());
    params = params.append("PageSize", this.pagesize.toString());
    this.ajax.get("/Task/List", params).then((res: any) => {
      this.tableloading = false;
      this.total = res.data.total;
      this.listOfCurrentPageData = res.data.rows;
      this.refreshCheckedStatus();
    });
  }
  loginout(): void {
    localStorage.removeItem("Authorization");
    this.router.navigate(["/login"]);

  }
  SshServer(): void {
    this.router.navigate(["/SshServer"])
  }
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }
  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.ID, value));
    this.refreshCheckedStatus();
  }
  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }
  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.ID));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.ID)) && !this.checked;
  }

  newTask(): void {
    this.visible = true;
    this.item = new TaskItems();
    this.item.RequestType = "get";
    this.urlmehtod = true;
  }
  deleteOne(): void {
    if (this.setOfCheckedId.size == 0) {
      this.message.info("请选择至少一项");
      return;
    }

    let ids: number[] | undefined = [];
    this.setOfCheckedId.forEach(x => ids!.push(x));
    this.item.ids = ids;
    this.ajax.post("/Task/Remove", this.item).then((res: any) => {
      if (res.code == 0) {
        this.message.success("删除成功！");
        this.searchData(true);
      } else {
        this.message.error(res.msg);
      }
    });

  }
  update(): void {
    if (this.setOfCheckedId.size != 1) {
      this.message.info("请选择一项");
      return;
    }
    let itemnew = new TaskItems();
    this.setOfCheckedId.forEach(x => itemnew.ID = x);
    this.item = this.listOfCurrentPageData.filter(x => x.ID == itemnew.ID)[0];
    this.MethodChange(this.item.RequestType);
    this.visible = true;
  }

  pauseTask(): void {
    if (this.setOfCheckedId.size == 0) {
      this.message.info("请选择至少一项");
      return;
    }
    let ids: number[] | undefined = [];
    this.setOfCheckedId.forEach(x => ids!.push(x));
    this.item.ids = ids;
    this.ajax.post("/Task/Pause", this.item).then((res: any) => {
      if (res.code == 0) {
        this.message.success("暂停成功！");
        this.searchData(true);
      } else {
        this.message.error(res.msg);
      }
    });

  }
  startTask(): void {
    if (this.setOfCheckedId.size == 0) {
      this.message.info("请选择至少一项");
      return;
    }
    let ids: number[] | undefined = [];
    this.setOfCheckedId.forEach(x => ids!.push(x));
    this.item.ids = ids;
    this.ajax.post("/Task/Start", this.item).then((res: any) => {
      if (res.code == 0) {
        this.message.success("开始任务！");
        this.searchData(true);
      } else {
        this.message.error(res.msg);
      }
    });

  }
  execteTask(): void {

    if (this.setOfCheckedId.size != 1) {
      this.message.info("请选择一项");
      return;
    }
    let itemnew = new TaskItems();
    this.setOfCheckedId.forEach(x => itemnew.ID = x);
    console.log(itemnew)
    this.ajax.post("/Task/Run", itemnew).then((res: any) => {
      if (res.code == 0) {
        this.message.success("执行成功！");
      } else {
        this.message.error(res.msg);
      }
    });
  }
  AddOrEditTask(): void {
    if (this.isEmpty(this.item.TaskName)) {
      this.message.error("任务名称不能为空");
      return;
    }
    if (this.isEmpty(this.item.GroupName)) {
      this.message.error("分组名称不能为空");
      return;
    }
    if (this.isEmpty(this.item.Interval)) {
      this.message.error("间隔(Cron)不能为空");
      return;
    }
    if (this.item.RequestType == "shell" && this.isEmpty(this.item.shell)) {
      this.message.error("脚本不能为空");
      return;
    }
    if (this.item.RequestType == "get" || this.item.RequestType == "post") {
      if (this.isEmpty(this.item.ApiUrl)) {
        this.message.error("url不能为空");
        return;
      }
    }
    this.ajax.post("/Task/AddOrEdit", this.item).then((res: any) => {
      if (res.code == 0) {
        this.message.success("提交成功！");
        this.close();
        this.searchData();
      } else {
        this.message.error(res.msg);
      }
    })
  }

  MethodChange(value: string|undefined): void {
    switch (value) {
      case "shell":
        this.urlmehtod = false;
        this.getSshSelect();
        break;

      default:
        this.urlmehtod = true;

        break;
    }
  }

  getSshSelect():void{
    this.ajax.get("/SshServer/Select","").then((res:any)=>{
        this.sshoptionlist=res.data;
    });
  }
  close(): void {
    this.visible = false;
  }
  isEmpty(str: string|undefined): boolean {
    if (str == undefined) {

      return true;
    }
    if (str.trim().length === 0) {
      return true;
    }
    if (str.replace(" ", "").length === 0) {
      return true;
    }
    return false;

  }
  
  logtaskname = "";
  loggroupname = "";
  hisTask(item: TaskItems): void {
    this.logtaskname = item.TaskName!;
    this.loggroupname = item.GroupName!;
    this.logsearchData(true);
    this.isModelVisible = true;
  }
  handleCancel(): void {
    this.isModelVisible = false;
  }
  handleOk(): void {
    this.isModelVisible = false;

  }
  logsearchData(reset: boolean = false) {
    if (reset) {
      this.pageindex = 1;
    }
    this.logtableloading = true;
    let params = new HttpParams();
    params = params.append("PageIndex", this.logpageindex.toString());
    params = params.append("PageSize", this.logpagesize.toString());
    params = params.append("taskname", this.logtaskname);
    params = params.append("groupname", this.loggroupname);
    this.ajax.get("/Task/Logs", params).then((res: any) => {
      this.logtableloading = false;
      this.logtotal = res.data.total;
      this.logcurrentdata = res.data.rows;
    });
  }

}
